import 'package:get/get.dart';
import 'package:dio/dio.dart' as dio;
import 'logger_service.dart';

/// API 服务 - API Service
/// 负责处理所有网络请求和 API 调用
class ApiService extends GetxService {
  static ApiService get to => Get.find();

  late dio.Dio _dio;
  
  // API 基础配置 - API Base Configuration
  static const String baseUrl = 'https://api.example.com';
  static const int connectTimeout = 30000;
  static const int receiveTimeout = 30000;

  @override
  Future<void> onInit() async {
    super.onInit();
    await _initializeDio();
    LoggerService.info('API 服务初始化完成 - API Service initialized');
  }

  /// 初始化 Dio - Initialize Dio
  Future<void> _initializeDio() async {
    _dio = dio.Dio(dio.BaseOptions(
      baseUrl: baseUrl,
      connectTimeout: const Duration(milliseconds: connectTimeout),
      receiveTimeout: const Duration(milliseconds: receiveTimeout),
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
      },
    ));

    // 添加拦截器 - Add Interceptors
    _dio.interceptors.add(
      dio.InterceptorsWrapper(
        onRequest: (options, handler) {
          LoggerService.info('API 请求: ${options.method} ${options.path}');
          handler.next(options);
        },
        onResponse: (response, handler) {
          LoggerService.info('API 响应: ${response.statusCode} ${response.requestOptions.path}');
          handler.next(response);
        },
        onError: (error, handler) {
          LoggerService.error('API 错误: ${error.message}', error: error);
          handler.next(error);
        },
      ),
    );
  }

  /// GET 请求 - GET Request
  Future<dio.Response<T>> get<T>(
    String path, {
    Map<String, dynamic>? queryParameters,
    dio.Options? options,
  }) async {
    try {
      return await _dio.get<T>(
        path,
        queryParameters: queryParameters,
        options: options,
      );
    } catch (e) {
      LoggerService.error('GET 请求失败 - GET request failed: $path', error: e);
      rethrow;
    }
  }

  /// POST 请求 - POST Request
  Future<dio.Response<T>> post<T>(
    String path, {
    dynamic data,
    Map<String, dynamic>? queryParameters,
    dio.Options? options,
  }) async {
    try {
      return await _dio.post<T>(
        path,
        data: data,
        queryParameters: queryParameters,
        options: options,
      );
    } catch (e) {
      LoggerService.error('POST 请求失败 - POST request failed: $path', error: e);
      rethrow;
    }
  }

  /// PUT 请求 - PUT Request
  Future<dio.Response<T>> put<T>(
    String path, {
    dynamic data,
    Map<String, dynamic>? queryParameters,
    dio.Options? options,
  }) async {
    try {
      return await _dio.put<T>(
        path,
        data: data,
        queryParameters: queryParameters,
        options: options,
      );
    } catch (e) {
      LoggerService.error('PUT 请求失败 - PUT request failed: $path', error: e);
      rethrow;
    }
  }

  /// DELETE 请求 - DELETE Request
  Future<dio.Response<T>> delete<T>(
    String path, {
    dynamic data,
    Map<String, dynamic>? queryParameters,
    dio.Options? options,
  }) async {
    try {
      return await _dio.delete<T>(
        path,
        data: data,
        queryParameters: queryParameters,
        options: options,
      );
    } catch (e) {
      LoggerService.error('DELETE 请求失败 - DELETE request failed: $path', error: e);
      rethrow;
    }
  }

  /// 设置认证令牌 - Set Authentication Token
  void setAuthToken(String token) {
    _dio.options.headers['Authorization'] = 'Bearer $token';
    LoggerService.info('认证令牌已设置 - Authentication token set');
  }

  /// 清除认证令牌 - Clear Authentication Token
  void clearAuthToken() {
    _dio.options.headers.remove('Authorization');
    LoggerService.info('认证令牌已清除 - Authentication token cleared');
  }

  /// 检查网络连接 - Check Network Connection
  Future<bool> checkConnection() async {
    try {
      final response = await _dio.get('/health');
      return response.statusCode == 200;
    } catch (e) {
      LoggerService.warning('网络连接检查失败 - Network connection check failed');
      return false;
    }
  }
}